package com.smart.translator.ui.ota;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.smart.translator.R;
import com.smart.translator.ble.BleManager;
import com.smart.translator.ota.OtaManager;
import com.smart.translator.ota.OtaManager.OtaType;
import com.smart.translator.ota.OtaUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.widget.RadioGroup;
import android.widget.RadioButton;

public class OtaUpdateActivity extends AppCompatActivity implements OtaManager.OtaCallback {
    private static final String TAG = "OtaUpdateActivity";
    private static final int REQUEST_CODE_PICK_FILE = 1001;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 1002;
    
    // UI组件
    private TextView tvDeviceStatus;
    private TextView tvSelectedFile;
    private Button btnSelectFile;
    private Button btnUpdate;
    private LinearLayout layoutProgress;
    private ProgressBar progressBar;
    private TextView tvProgress;
    private TextView tvStatus;
    private RadioGroup rgOtaType;
    private RadioButton rbCm3;
    private RadioButton rbDsp;
    private RadioButton rbExternalFlash;
    private Button btnReadCm3Base;
    private Button btnReadDspBase;
    private Button btnReadExternalFlashBase;
    
    // OTA管理器
    private OtaManager otaManager;
    private BleManager bleManager;
    
    // 文件相关
    private String selectedFirmwarePath;
    private boolean isFileSelected = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ota_update);
        
        initViews();
        initOtaManager();
        setupListeners();
    }
    
    private void initViews() {
        tvDeviceStatus = findViewById(R.id.tv_device_status);
        tvSelectedFile = findViewById(R.id.tv_selected_file);
        btnSelectFile = findViewById(R.id.btn_select_file);
        btnUpdate = findViewById(R.id.btn_update);
        layoutProgress = findViewById(R.id.layout_progress);
        progressBar = findViewById(R.id.progress_bar);
        tvProgress = findViewById(R.id.tv_progress);
        tvStatus = findViewById(R.id.tv_status);
        rgOtaType = findViewById(R.id.rg_ota_type);
        rbCm3 = findViewById(R.id.rb_cm3);
        rbDsp = findViewById(R.id.rb_dsp);
        rbExternalFlash = findViewById(R.id.rb_external_flash);
        btnReadCm3Base = findViewById(R.id.btn_read_cm3_base);
        btnReadDspBase = findViewById(R.id.btn_read_dsp_base);
        btnReadExternalFlashBase = findViewById(R.id.btn_read_external_flash_base);
        
        // 设置返回按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());
        
        // 不要在这里调用updateOtaTypeAvailability();
    }
    
    private void initOtaManager() {
        // 初始化OTA管理器
        otaManager = OtaManager.getInstance();
        bleManager = BleManager.getInstance();
        otaManager.init(this, bleManager);
        otaManager.setCallback(this);
        
        // 检查设备连接状态
        updateDeviceStatus();
        // 这里再调用，保证otaManager已初始化
        updateOtaTypeAvailability();
    }
    
    private void setupListeners() {
        btnSelectFile.setOnClickListener(v -> {
            if (checkStoragePermission()) {
                selectFirmwareFile();
            } else {
                requestStoragePermission();
            }
        });
        
        btnUpdate.setOnClickListener(v -> {
            if (isFileSelected) {
                startOtaUpdate();
            } else {
                showToast("请先选择固件文件");
            }
        });
        btnReadCm3Base.setOnClickListener(v -> readBaseAddress(OtaType.CM3));
        btnReadDspBase.setOnClickListener(v -> readBaseAddress(OtaType.DSP));
        btnReadExternalFlashBase.setOnClickListener(v -> readBaseAddress(OtaType.EXTERNAL_FLASH));
    }
    
    private void updateDeviceStatus() {
        if (bleManager.isConnected()) {
            tvDeviceStatus.setText("已连接");
            tvDeviceStatus.setTextColor(ContextCompat.getColor(this, android.R.color.holo_green_dark));
        } else {
            tvDeviceStatus.setText("未连接");
            tvDeviceStatus.setTextColor(ContextCompat.getColor(this, android.R.color.holo_red_dark));
        }
        
        // 更新OTA类型可用性
        updateOtaTypeAvailability();
    }
    
    private void updateOtaTypeAvailability() {
        // 检查CM3 OTA是否可用
        boolean cm3Available = otaManager.isCm3OtaAvailable();
        rbCm3.setEnabled(cm3Available);
        if (!cm3Available) {
            rbCm3.setText("CM3程序 (不可用)");
        } else {
            rbCm3.setText("CM3程序");
        }
        
        // 检查DSP OTA是否可用
        boolean dspAvailable = otaManager.isDspOtaAvailable();
        rbDsp.setEnabled(dspAvailable);
        if (!dspAvailable) {
            rbDsp.setText("DSP程序 (不可用)");
        } else {
            rbDsp.setText("DSP程序");
        }
        
        // 检查外部Flash OTA是否可用
        boolean externalFlashAvailable = otaManager.isExternalFlashOtaAvailable();
        rbExternalFlash.setEnabled(externalFlashAvailable);
        if (!externalFlashAvailable) {
            rbExternalFlash.setText("外部Flash程序 (不可用)");
        } else {
            rbExternalFlash.setText("外部Flash程序");
        }
        
        // 如果没有可用的OTA类型，禁用更新按钮
        if (!cm3Available && !dspAvailable && !externalFlashAvailable) {
            btnUpdate.setEnabled(false);
            btnUpdate.setText("无可用OTA服务");
        } else if (isFileSelected) {
            btnUpdate.setEnabled(true);
            btnUpdate.setText("开始更新");
        }
    }
    
    private boolean checkStoragePermission() {
        // Android 10 (API 29) 及以上版本使用分区存储，不需要READ_EXTERNAL_STORAGE权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            return true;
        }
        
        return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
               == PackageManager.PERMISSION_GRANTED;
    }
    
    private void requestStoragePermission() {
        // Android 10 及以上版本不需要申请存储权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            selectFirmwareFile();
            return;
        }
        
        // 检查是否应该显示权限说明
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // 显示权限说明对话框
            new AlertDialog.Builder(this)
                .setTitle("需要存储权限")
                .setMessage("为了选择固件文件，应用需要访问存储权限。请在接下来的对话框中允许权限。")
                .setPositiveButton("确定", (dialog, which) -> {
                    ActivityCompat.requestPermissions(this, 
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
                        REQUEST_CODE_STORAGE_PERMISSION);
                })
                .setNegativeButton("取消", null)
                .show();
        } else {
            // 直接申请权限
            ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
                REQUEST_CODE_STORAGE_PERMISSION);
        }
    }
    
    private void selectFirmwareFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
    }
    
    private void startOtaUpdate() {
        if (selectedFirmwarePath == null) {
            showToast("请先选择固件文件");
            return;
        }
        
        // 显示确认对话框
        new AlertDialog.Builder(this)
            .setTitle("确认更新")
            .setMessage("确定要更新设备固件吗？更新过程中请勿断开设备连接。")
            .setPositiveButton("确定", (dialog, which) -> {
                performOtaUpdate();
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    private void performOtaUpdate() {
        // 获取选中的OTA类型
        OtaType selectedType = OtaType.CM3;
        if (rbCm3.isChecked()) {
            selectedType = OtaType.CM3;
        } else if (rbDsp.isChecked()) {
            selectedType = OtaType.DSP;
        } else if (rbExternalFlash.isChecked()) {
            selectedType = OtaType.EXTERNAL_FLASH;
        }
        
        // 检查选择的OTA类型是否可用
        if (selectedType == OtaType.CM3 && !otaManager.isCm3OtaAvailable()) {
            showToast("CM3 OTA服务不可用");
            return;
        }
        if (selectedType == OtaType.DSP && !otaManager.isDspOtaAvailable()) {
            showToast("DSP OTA服务不可用");
            return;
        }
        if (selectedType == OtaType.EXTERNAL_FLASH && !otaManager.isExternalFlashOtaAvailable()) {
            showToast("外部Flash OTA服务不可用");
            return;
        }
        
        // 禁用更新按钮
        btnUpdate.setEnabled(false);
        btnUpdate.setText("更新中...");
        
        // 显示进度条
        layoutProgress.setVisibility(View.VISIBLE);
        
        // 开始OTA更新
        otaManager.startUpdate(selectedFirmwarePath, selectedType, this);
    }
    
    private void readBaseAddress(OtaType otaType) {
        if (!bleManager.isConnected()) {
            showToast("请先连接设备");
            return;
        }
        otaManager.readBaseAddress(otaType, (baseAddr, version) -> {
            runOnUiThread(() -> {
                showToast(otaType.getDisplayName() + "基地址: 0x" + Integer.toHexString(baseAddr) + "\n版本: " + version);
            });
        });
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_CODE_PICK_FILE && resultCode == Activity.RESULT_OK && data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                handleFileSelection(uri);
            }
        }
    }
    
    private void handleFileSelection(Uri uri) {
        try {
            // 获取文件名
            String fileName = getFileName(uri);
            if (fileName == null) {
                fileName = "固件文件";
            }
            
            // 复制文件到应用内部存储
            File internalFile = copyFileToInternalStorage(uri, fileName);
            if (internalFile != null) {
                selectedFirmwarePath = internalFile.getAbsolutePath();
                isFileSelected = true;
                
                // 更新UI
                tvSelectedFile.setText("已选择: " + fileName);
                tvSelectedFile.setTextColor(ContextCompat.getColor(this, android.R.color.holo_blue_dark));
                btnUpdate.setEnabled(true);
                
                // 验证文件
                if (OtaUtils.isValidFirmwareFile(selectedFirmwarePath)) {
                    showToast("固件文件验证通过");
                } else {
                    showToast("警告: 固件文件格式可能不支持");
                }
            } else {
                showToast("文件复制失败");
            }
        } catch (Exception e) {
            Log.e(TAG, "处理文件选择失败", e);
            Toast.makeText(this, "文件处理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private String getFileName(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (android.database.Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME);
                    if (index >= 0) {
                        result = cursor.getString(index);
                    }
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }
    
    private File copyFileToInternalStorage(Uri uri, String fileName) {
        try {
            File internalDir = getFilesDir();
            File destFile = new File(internalDir, "firmware_" + System.currentTimeMillis() + "_" + fileName);
            
            try (InputStream is = getContentResolver().openInputStream(uri);
                 FileOutputStream fos = new FileOutputStream(destFile)) {
                
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, length);
                }
            }
            
            Log.d(TAG, "文件复制成功: " + destFile.getAbsolutePath());
            return destFile;
        } catch (Exception e) {
            Log.e(TAG, "文件复制失败", e);
            return null;
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_CODE_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限获取成功，选择文件
                selectFirmwareFile();
            } else {
                // 权限被拒绝
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    // 用户拒绝了权限但没有勾选"不再询问"
                    showToast("需要存储权限来选择固件文件，请在设置中手动开启权限");
                } else {
                    // 用户勾选了"不再询问"
                    showPermissionDeniedDialog();
                }
            }
        }
    }
    
    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(this)
            .setTitle("权限被拒绝")
            .setMessage("存储权限被拒绝，无法选择固件文件。请在设置中手动开启存储权限。")
            .setPositiveButton("去设置", (dialog, which) -> {
                // 打开应用设置页面
                try {
                    Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(android.net.Uri.fromParts("package", getPackageName(), null));
                    startActivity(intent);
                } catch (Exception e) {
                    Log.e(TAG, "打开设置页面失败", e);
                    showToast("无法打开设置页面，请手动开启存储权限");
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    // OTA回调实现
    @Override
    public void onProgress(int progress, String message) {
        runOnUiThread(() -> {
            progressBar.setProgress(progress);
            tvProgress.setText(progress + "%");
            tvStatus.setText(message);
        });
    }
    
    @Override
    public void onSuccess(String message) {
        runOnUiThread(() -> {
            showToast("固件更新成功！");
            updateProgress(100, "更新完成");
            btnUpdate.setEnabled(true);
            btnUpdate.setText("更新完成");
            showUpdateCompletedDialog();
        });
    }
    
    @Override
    public void onError(String error) {
        runOnUiThread(() -> {
            showToast("更新失败: " + error);
            updateProgress(0, "更新失败");
            btnUpdate.setEnabled(true);
            btnUpdate.setText("重新更新");
            showUpdateErrorDialog(error);
        });
    }
    
    @Override
    public void onVersionReceived(String version) {
        Log.d(TAG, "收到版本信息: " + version);
        runOnUiThread(() -> {
            showToast("设备版本: " + version);
        });
    }
    
    @Override
    public void onVersionReceived(OtaManager.OtaType otaType, String version) {
        Log.d(TAG, "收到" + otaType.getDisplayName() + "版本信息: " + version);
        runOnUiThread(() -> {
            String message = otaType.getDisplayName() + "版本: " + version;
            showToast(message);
        });
    }
    
    @Override
    public void onVersionCheckComplete() {
        Log.d(TAG, "版本检查完成");
        runOnUiThread(() -> {
            showToast("版本检查完成");
        });
    }
    
    private void updateProgress(int progress, String message) {
        progressBar.setProgress(progress);
        tvProgress.setText(progress + "%");
        tvStatus.setText(message);
    }
    
    private void showUpdateCompletedDialog() {
        new AlertDialog.Builder(this)
            .setTitle("更新完成")
            .setMessage("固件更新已完成，设备将自动重启。")
            .setPositiveButton("确定", (dialog, which) -> {
                finish();
            })
            .setCancelable(false)
            .show();
    }
    
    private void showUpdateErrorDialog(String error) {
        new AlertDialog.Builder(this)
            .setTitle("更新失败")
            .setMessage("固件更新失败: " + error)
            .setPositiveButton("确定", (dialog, which) -> {
                // 重置状态
                layoutProgress.setVisibility(View.GONE);
                btnUpdate.setEnabled(isFileSelected);
                btnSelectFile.setEnabled(true);
            })
            .show();
    }
    
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (otaManager != null) {
            otaManager.stopOtaUpdate();
        }
    }
} 